$(function(){
	$("#submit").on("click",function(){
		var cname = $("input").eq(0).val();   
		var sex = $('input:radio:checked').val();
		var sal = $("input").eq(3).val();
		var birth = $("input").eq(4).val();
		var customer = {cname:cname, sex:sex, sal:sal, birth:birth};
		
		var json = JSON.stringify(customer);
		$.ajax({
			type:"POST",
			url:"addCustomer",
			data:json,
			contentType:"application/json"
		}).done(function(data){
			createTable(data);
		});
	});
});


function createTable(data){
	i = 0;
	var tr = $("<tr>");
	$("#tableId").append(tr);
	tr.append($("<td>").text(data.cname));
	var sex = '男';
	if(!data.sex)
		sex = '女';
	tr.append($("<td>").text(sex));
	tr.append($("<td>").text(data.sal));
	tr.append($("<td>").text(dateFormat(data.birth)));
	tr.append($("<td>").append($('<button class="">del</button>').attr("id", data.id)));
	delListener();
}

function delListener(){
	$("#tableId button").on("click", function(e){
		var x = $(this).attr("id");
        $.ajax({
            type:"POST",
            url:"deleteCustomer?id=" + x,
        }).done(function(msg){
            var id="#"+x;
            var p = $(id).parent().parent().remove();
        });
    });
}
function dateFormat(time){
    var birth = new Date(time);
    var month = birth.getMonth()+1;
    if (birth.getMonth()+1<10){
        var month = "0" + (birth.getMonth()+1);
    }
    var dat = birth.getDate();
    if (birth.getDate() < 10){
        var dat = "0" + birth.getDate();
    }
    return birth.getFullYear()+"-"+month+"-"+dat;
}